package com.ams.xfdbs.pool;

import java.util.concurrent.*;

public class CommonThreadPoolExecutor {
    private static ThreadPoolExecutor threadPoolExecutor;

    public static final int CORE_THREAD = Runtime.getRuntime().availableProcessors() + 1;

    private static final int MAX_THREAD = Runtime.getRuntime().availableProcessors() * 2;

    private static final int MAX_BLOCK_SIZE = 1000;

    private static final long KEEP_ALIVE = 1000;

    public static ThreadPoolExecutor getThreadExecutor() {
        if (threadPoolExecutor == null) {
            synchronized (CommonThreadPoolExecutor.class) {
                if (threadPoolExecutor == null) {
                    threadPoolExecutor = new java.util.concurrent.ThreadPoolExecutor(CORE_THREAD,
                            MAX_THREAD,
                            KEEP_ALIVE,
                            TimeUnit.SECONDS,
                            new LinkedBlockingQueue<>(MAX_BLOCK_SIZE),
                            Executors.defaultThreadFactory(),
                            new ThreadPoolExecutor.AbortPolicy());
                }
            }
        }
        return threadPoolExecutor;
    }

    public static void execute(Runnable runnable) {
        getThreadExecutor().execute(runnable);
    }

    public static Future<?> submit(Runnable runnable) {
        return getThreadExecutor().submit(runnable);
    }

    public static <T>Future<T> submit(Callable<T> callable) {
        return getThreadExecutor().submit(callable);
    }
}
